package com.czkevin.biliwsclient;

import com.alibaba.fastjson.JSONObject;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BiliSession {

  public final String uuid;

  public final String session;

  public final String biliJct;

  public final String csrfToken;

  public BiliSession(String uuid, String session, String biliJct, String csrfToken) {
    this.uuid = uuid;
    this.session = session;
    this.biliJct = biliJct;
    this.csrfToken = csrfToken;
  }

  public String generateHttpPostFormBody(Map<String, String> params) {
    final Map<String, String> finalParams = new HashMap<>(params);
    if(csrfToken != null) {
      finalParams.put("csrf", csrfToken);
      finalParams.put("csrf_token", csrfToken);
    }

    final List<String> pairs = new ArrayList<>(finalParams.size());
    finalParams.forEach((k, v) -> {
      try {
        pairs.add(
            String.format("%s=%s", URLEncoder.encode(k, "UTF-8"), URLEncoder.encode(v, "UTF-8"))
        );
      } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
      }
    });

    StringBuilder sb = new StringBuilder();
    if(pairs.size() == 1) {
      return pairs.get(0);
    } else {
      for(int i = 0; i < pairs.size() - 1; i++) {
        sb.append(pairs.get(i));
        if(i != pairs.size() - 1) {
          sb.append("&");
        }
      }
      return sb.toString();
    }
  }

  public String doPostForm(Map<String, String> params, String url, int room) throws IOException {
    final Map<String, String> finalParams = new HashMap<>(params);
    if(csrfToken != null) {
      finalParams.put("csrf", csrfToken);
      finalParams.put("csrf_token", csrfToken);
    }
    return HTTPHelper.doPostForm(url, finalParams, room, this, null);
  }

  public static BiliSession fromConfig(File jsonConfig) {
    final JSONObject jsonSession = JSONHelper.loadJson(jsonConfig);
    final BiliSession biliSession = new BiliSession(
        jsonSession.getString("uuid"),
        jsonSession.getString("session"),
        jsonSession.getString("bili_jct"),
        jsonSession.getString("csrf_token")
    );
    return biliSession;
  }

}
